<template>
  <el-card>
    <el-form inline class="form">
      <el-form-item label="用户名">
        <el-input placeholder="请输入用户名" v-model="keyword"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :disabled="!keyword" @click="onSearch">
          搜索
        </el-button>
        <el-button type="primary" @click="onReset">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
  <el-card style="margin: 10px 0">
    <el-button type="primary" icon="Plus" @click="onAddRole">
      添加职位
    </el-button>
    <el-table style="margin: 20px 0" border stripe :data="allRoleList">
      <el-table-column
        label="#"
        type="index"
        align="center"
        width="50px"
      ></el-table-column>
      <el-table-column label="ID" align="center" prop="id"></el-table-column>
      <el-table-column
        label="职位名称"
        align="center"
        prop="roleName"
      ></el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        show-overflow-tooltip
        prop="createTime"
      ></el-table-column>
      <el-table-column
        label="更新时间"
        align="center"
        show-overflow-tooltip
        prop="updateTime"
      ></el-table-column>
      <el-table-column label="操作" align="center" width="300px">
        <template #="{ row, $index }">
          <el-button
            type="success"
            size="small"
            icon="User"
            @click="onSetAuthority(row)"
          >
            分配权限
          </el-button>
          <el-button
            type="primary"
            size="small"
            icon="Edit"
            @click="onEdit(row)"
          >
            编辑
          </el-button>
          <el-popconfirm
            :title="`你确定要删除${row.roleName}？`"
            width="260px"
            @confirm="onRemoveRole(row.id)"
          >
            <template #reference>
              <el-button type="danger" size="small" icon="Delete">
                删除
              </el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <!--分页器-->
    <el-pagination
      v-model:current-page="pageNo"
      v-model:page-size="pageSize"
      :background="true"
      :page-sizes="[10, 20, 30, 40]"
      layout=" prev, pager, next, jumper,->, sizes,total"
      :total="total"
      @current-change="getHasRole"
      @size-change="sizeChange"
    />
  </el-card>
  <!--添加、更新-->
  <el-dialog
    v-model="dialogVisible"
    :title="roleParams.id ? '添加职位' : '添加职位'"
  >
    <el-form :model="roleParams" :rules="rules" ref="form">
      <el-form-item label="职位名称" prop="roleName">
        <el-input placeholder="请输入职位名称" v-model="roleParams.roleName"/>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button type="primary" @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="onSave">确定</el-button>
    </template>
  </el-dialog>
  <!--权限抽屉-->
  <el-drawer v-model="drawer">
    <template #header>
      <h4>分配菜单与按钮权限</h4>
    </template>
    <template #default>
      <el-tree
        ref="tree"
        :data="menuArr"
        :props="defaultProps"
        :default-checked-keys="selectArr"
        default-expand-all
        node-key="id"
        show-checkbox
      />
    </template>
    <template #footer>
      <el-button type="primary" @click="drawer = false">取消</el-button>
      <el-button type="primary" @click="onHandler">确定</el-button>
    </template>
  </el-drawer>
</template>
<script setup lang="ts">
import {nextTick, onMounted, reactive, ref} from 'vue'
import {
  reqAddOrUpdateRole,
  reqAllMenuList,
  reqAllRoleList,
  reqRemoveRole,
  reqSetPermisstion,
} from '@/api/acl/role'
import type {
  MenuList,
  MenuResponseData,
  Records,
  RoleData,
  RoleResponseData,
} from '@/api/acl/role/type'
import useLayoutSettingStore from '@/store/modules/setting'
import {ElMessage} from 'element-plus'

let keyword = ref<string>('')
let pageNo = ref<number>(1)
let pageSize = ref<number>(10)
let total = ref<number>(0)
// 存储全部已有的职位
let allRoleList = ref<Records>([])
let settingStore = useLayoutSettingStore()
let dialogVisible = ref<boolean>(false)
// 收集新增岗位数据
let roleParams = reactive<RoleData>({
  roleName: '',
})
// 获取form组件实例
let form = ref<any>()
// 显示、隐藏抽屉
let drawer = ref<boolean>(false)
// 存储用户权限的数据
let menuArr = ref<MenuList>([])
// 树形控件数据
const defaultProps = {
  children: 'children',
  label: 'name',
}
// 存储勾选节点的ID
let selectArr = ref<number[]>([])
// 获取树形控件
let tree = ref<any>()

onMounted(() => {
  getHasRole()
})

// 获取数据
const getHasRole = async (pager = 1) => {
  pageNo.value = pager
  let result: RoleResponseData = await reqAllRoleList(
    pageNo.value,
    pageSize.value,
    keyword.value,
  )
  if (result.code === 200) {
    allRoleList.value = result.data.records
    total.value = result.data.total
  }
}

// 分页器条数
const sizeChange = () => {
  getHasRole()
}

// 点击搜索
const onSearch = () => {
  getHasRole()
  keyword.value = ''
}
// 点击重置
const onReset = () => {
  settingStore.refresh = !settingStore.refresh
}
// 点击添加职位
const onAddRole = () => {
  dialogVisible.value = true
  Object.assign(roleParams, {
    roleName: '',
    id: 0,
  })
  nextTick(() => {
    form.value.clearValidate('roleName')
  })
}
// 点击分配权限
const onSetAuthority = async (row: RoleData) => {
  drawer.value = true
  Object.assign(roleParams, row)
  let result: MenuResponseData = await reqAllMenuList(roleParams.id)
  if (result.code === 200) {
    menuArr.value = result.data
    selectArr.value = filterSelectArr(menuArr.value, [])
  }
}
// 点击编辑
const onEdit = (row: RoleData) => {
  dialogVisible.value = true
  Object.assign(roleParams, row)
  nextTick(() => {
    form.value.clearValidate('roleName')
  })
}
const validatorRoleName = (rule: any, value: any, callBack: any) => {
  if (value.trim().length >= 2) {
    callBack()
  } else {
    callBack(new Error('职位名称至少两位'))
  }
}
// 表单校验
const rules = {
  roleName: [{required: true, trigger: 'blur', validator: validatorRoleName}],
}
// 点击确定
const onSave = async () => {
  await form.value.validate()
  let result: any = await reqAddOrUpdateRole(roleParams)
  if (result.code === 200) {
    ElMessage({
      type: 'success',
      message: roleParams.id ? '更新成功' : '添加成功',
    })
    dialogVisible.value = false
    await getHasRole(roleParams.id ? pageNo.value : 1)
  }
}
// 递归遍历
const filterSelectArr = (allData: any, initArr: any) => {
  allData.forEach(
    (item: { level: number; children: any; select: boolean; id: number }) => {
      if (item.select && item.children.length === 0) {
        initArr.push(item.id)
      }
      if (item.children && item.children.length > 0) {
        filterSelectArr(item.children, initArr)
      }
    },
  )
  return initArr
}
// 点击权限确定
const onHandler = async () => {
  const roleId = roleParams.id
  let arr = tree.value.getCheckedKeys()
  let arr1 = tree.value.getHalfCheckedKeys()
  let permissionId = arr.concat(arr1)
  let result: any = await reqSetPermisstion(roleId, permissionId)
  if (result.code === 200) {
    drawer.value = false
    ElMessage({type: 'success', message: '分配权限成功'})
    window.location.reload()
  }
}
// 点击删除
const onRemoveRole = async (id: number) => {
  let result: any = await reqRemoveRole(id)
  if (result.code === 200) {
    ElMessage({type: 'success', message: '删除成功'})
    await getHasRole(
      allRoleList.value.length > 1 ? pageNo.value : pageNo.value - 1,
    )
  } else {
    return ElMessage({type: 'error', message: result.data})
  }
}
</script>
<style scoped lang="scss">
.form {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
